<template>
  <div>
    <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :visible.sync="visible"
      :close-on-click-modal="false"
      width="500px">
      <el-form
        :model="dataForm"
        :rules="dataRule"
        @keyup.enter.native="dataFormSubmit()"
        ref="dataForm"
        label-width="100px">
          <el-form-item label="新密码:" prop="password">
            <el-input type="password" v-model="dataForm.password" placeholder="新密码"></el-input>
          </el-form-item>
          <el-form-item label="确认密码:" prop="confirmPassword">
            <el-input type="password"  v-model="dataForm.confirmPassword" placeholder="确认密码"></el-input>
          </el-form-item>
          <el-form-item>
            <div style="color:#E6A23C;fontSize:12px;">密码必须由6-16位字母或数字组成</div>
          </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button  @click="visible = false">取消</el-button>
      <el-button  type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'changePassword',
    data () {
      var validateConfirmPassword = (rule, value, callback) => {
        if (this.dataForm.password !== value) {
          callback(new Error('确认密码与新密码不一致'))
        } else {
          let rexp = /^[a-z0-9A-Z]{6,16}$/
          if (rexp.test(value)) {
            callback()
          } else {
            callback(new Error('密码必须由6-16位字母和数字组成'))
          }
        }
      }
      return {
        visible: false,
        dataForm: {
          password: '',
          confirmPassword: '',
          userId: ''
        },
        dataList: [],
        dataRule: {
          password: [
            { required: true, message: '密码不能为空', trigger: 'blur' }
          ],
          confirmPassword: [
            { required: true, message: '确认密码不能为空', trigger: 'blur' },
            { validator: validateConfirmPassword, trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          this.dataForm.userId = id
        })
      },
      async dataFormSubmit () {
        let valid = await this.$refs.dataForm.validate()
        if (!valid) return

        let res = await this.$http({
          url: this.$http.adornUrl(`/usercenter-admin/user/modifyPassword`),
          method: 'post',
          data: {
            'userId': this.dataForm.userId,
            'password': this.dataForm.password,
            'checkPassword': this.dataForm.confirmPassword
          }
        })

        if (res && res.code === 200) {
          this.$notify.success({title: '成功', message: '修改密码成功'})
          this.visible = false
        } else {
          this.$notify.error({title: '错误', message: res.msg})
        }
      }
    }
  }
</script>

<style scoped>

</style>
